package com.pes.arcww.dao;

import java.util.Collection;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.pes.arcww.form.Profiles;
import com.pes.arcww.form.Topics;

@Repository
public class ProfilesDAOImpl implements ProfilesDAO{

	@Autowired
	private SessionFactory sessionFactory;
	
	public void addProfile(Profiles profile) {
		sessionFactory.getCurrentSession().save(profile);
	}
	
	public void addTopic(Integer pro_id, Integer top_id) {
		Topics topic = getTopic(top_id);
		Profiles profile = getProfile(pro_id);
		
		profile.getTopicsList().add(topic);
		updateProfile(profile);
	}

	@SuppressWarnings("unchecked")
	public Collection<Profiles> listProfiles(String filter, String value) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Profiles.class);
		
		if(filter.equals("") && value.equals("")){
			criteria.addOrder(Order.desc("pro_id"));
		}else if(filter.equals("id")){
			criteria.add(Restrictions.sqlRestriction(" pro_id LIKE '%"+value+"%' ")).addOrder(Order.desc("pro_id"));
		}else if(filter.equals("title")){
			criteria.add(Restrictions.like("title", "%"+value+"%")).addOrder(Order.asc("title"));
		}else{//description
			criteria.add(Restrictions.like("description", "%"+value+"%")).addOrder(Order.asc("description"));
		}
		
		return criteria.list();
		
	}

	public void removeProfile(Integer id) {
		Profiles profile = getProfile(id);
		if(profile != null){
			sessionFactory.getCurrentSession().delete(profile);
		}
	}
	
	public void removetopic(Integer pro_id, Integer top_id) {

		Profiles profile = getProfile(pro_id);
		Collection <Topics> list = profile.getTopicsList();
		Topics t = new Topics();
		t.setId(top_id);
		list.remove(t);		
		profile.setTopicsList(list);
		updateProfile(profile);
	}

	public void updateProfile(Profiles profile) {
		sessionFactory.getCurrentSession().update(profile);
	}

	public Profiles getProfile(Integer id) {
		Profiles profile = (Profiles) sessionFactory.getCurrentSession().get(Profiles.class, id);
		return profile;
	}
	
	public Topics getTopic(Integer id) {
		Topics topic = (Topics) sessionFactory.getCurrentSession().get(Topics.class, id);
		return topic;
	}
}
